import Vue from 'vue'
import Vuex from '../vuex'

function persists(store) {
  let local = localStorage.getItem('VUEX:STATE')
  if(local) {
    store.replaceState(JSON.parse(local))
  }
  store.subscribe(({mutation}, state)=>{
    localStorage.setItem('VUEX:STATE', JSON.stringify(state))
  })
}


Vue.use(Vuex)
let store = new Vuex.Store({
  strict: true,  // 严格模式下 只能通过mutation 更改状态 其他都不行
  plugins: [
    persists
  ],

  state: {
    age: 28
  },
  getters: {
    getAge(state) {
      return state.age + 10
    }
  },
  mutations: {
    changeAge(state, payload) {
      state.age += payload
    }
  },
  actions: {
    changeAge({commit}, payload) {
      setTimeout(()=>{
        console.log('??/')
        commit('changeAge', payload)
      }, 1000)
    }
  },
  modules: {
    a: {
      state: {
        b: 11
      },
      modules: {
        aa: {
          state: {
            c: 22
          }
        }
      }
    },
    b: {
      state: {
        f: 223
      },
      modules: {
        dd: {
          state: {
            ee: 22
          }
        }
      }
    }
  }
})

store.registerModule('e', {
  state: {
    e: 111
  }
})

export default store